
# -*- coding: utf-8 -*-

import signal
import os.path
import logging
import tornado.web
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.websocket

from tornado.options import define, options
from util.util import initializeModel, tryConnectToUsersServer
from util.FacialRecognition import trainModel

from controllers.IndexController import IndexController
from controllers.LoginController import LoginController
from controllers.LogoutController import LogoutController
from controllers.MarkingsController import MarkingsController
from controllers.UserController import UserController
from controllers.LogsController import LogsController
from controllers.TrainController import TrainController
from controllers.StatisticsController import StatisticsController
from controllers.UploadPhotoSocketController import UploadPhotoSocketController
from controllers.UploadExtraPhotoSocketController import UploadExtraPhotoSocketController
from controllers.PredictController import PredictController

define("port", default=8888, help="Server listen port", type=int)

class Application(tornado.web.Application):
	def __init__(self):
		handlers = [
			(r"/", IndexController),
			(r"/users/login", LoginController),
			(r"/users/logout", LogoutController),
			(r"/users/.*", UserController),
			(r"/logs/.*", LogsController),
			(r"/statistics", StatisticsController),
			(r"/uploadphoto", UploadPhotoSocketController),
			(r"/extraphoto", UploadExtraPhotoSocketController),
			(r"/markings", MarkingsController),
			(r"/predict", PredictController),
			(r"/facedetector", PredictController),
			(r"/train", TrainController)
		]

		settings = dict(
			cookie_secret="asdsafasdqnknfkjqweonrkbknoijsd#$%^TFGFGjn",
			template_path=os.path.join(os.path.dirname(__file__), "templates"),
			static_path=os.path.join(os.path.dirname(__file__), "static"),
			xsrf_cookies=False,
			login_url="/users/login",
			autoescape=None,
			debug=True
		)

		tornado.web.Application.__init__(self, handlers, **settings)

def handleStopServer(signum, frame):
	logging.info("STOP Signal Received")
	tornado.ioloop.IOLoop.instance().stop()
	logging.info("Server Shutdown")

def main():
	tryConnectToUsersServer()
	initializeModel()
	trainModel()
	tornado.options.parse_command_line()
	app = Application()
	app.listen(options.port)
	logging.info("Server Ready")
	signal.signal(signal.SIGTERM, handleStopServer)
	signal.signal(signal.SIGINT, handleStopServer)
	tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
	main()
